<template>
  <div class="score-import">
    <!-- 文件选择和导入按钮 -->
 <Row style="display: flex" class="upload-file">
   <img src="../../assets/icons/unload.png" class="upload-icon"/>
   <van-field
       v-model="fileName"
       label="Excel 文件"
       readonly
       clickable
       input-align="right"
       style="font-size: 12px;margin-top: 5px"
       @click="chooseFile"

   />
 </Row>


    <!-- 表格 -->
    <table v-if="students.length > 0">
      <thead>
      <tr style="font-size: 14px">
        <th>姓名</th>
        <th>语文</th>
        <th>数学</th>
        <th>英语</th>
        <th>总分</th>
        <th>班级排名</th>
        <th>年级排名</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="student in students" :key="student.学号">
        <td>{{ student.studentName }}</td>
        <td>{{ student.chinese}}</td>
        <td>{{ student.math}}</td>
        <td>{{ student.english}}</td>
        <td>{{ student.totalScore}}</td>
        <td>{{ student.classRank}}</td>
        <td>{{ student.gradeRank}}</td>
      </tr>
      </tbody>
    </table>
  </div>
  <van-button class="import" @click="importScores">导入成绩</van-button>
</template>

<script setup>
import { ref } from 'vue';
import { Field, Button, Toast } from 'vant';
import axios from 'axios';
import * as XLSX from 'xlsx';

const fileName = ref(''); // 存储文件名
const students = ref([]); // 存储解析后的学生数据
const chooseFile = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx, .xls';
  input.onchange = e => {
    const files = e.target.files;
    if (files.length) {
      fileName.value = files[0].name; // 设置文件名
      const reader = new FileReader();
      reader.onload = e => {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: 'binary' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        let rawData = XLSX.utils.sheet_to_json(worksheet);
        console.log('Raw Data:', rawData); // 检查原始数据

        const processedData = rawData.map((item, index) => {
          return {
            studentId: parseInt(item.学号,),
            studentName: item.姓名,
            chinese: parseFloat(item.语文),
            math: parseFloat(item.数学),
            english: parseFloat(item.英语),
            totalScore: parseFloat(item.总分),
            classRank: parseInt(item.班级排名),
            gradeRank: parseInt(item.年级排名),
            className: item.班级
          };
        });

        students.value = processedData; // 使用处理过的数据填充学生数据
      };
      reader.readAsBinaryString(files[0]);
    }
  };
  input.click();
};

const importScores = async () => {
  if (!fileName.value) {
    Toast.fail('请选择文件');
    return;
  }

  // 这里可以添加上传文件的逻辑，例如发送 AJAX 请求到后端
  // 假设使用文件名作为考试名称
  try {
    const examName = fileName.value.replace('.xlsx', ''); // 去掉.xlsx后缀名
    const response = await axios.get(`/api/exams/add?examsName=${encodeURIComponent(examName)}`);

    // 假设后端API需要学生数据列表
    console.log("student data:"+students.value)
    const examsId = parseInt(response.data, 10);
    const importResponse = await axios.post(`/api/totalScore/import/${examsId}`, students.value, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
   console.log("importResponse:"+JSON.stringify(importResponse.data))
    if (importResponse.data.code === 2000) {
      Toast.success('导入成绩成功');
    } else {
      Toast.fail('导入成绩失败');
    }
  } catch (error) {
    console.error('Error importing scores:', error);
    Toast.fail('导入成绩失败');
  }

};
</script>

<style scoped>

.score-import {
  margin: 20px;
}

.upload-file{
  border: 2px solid  #9caf70;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效 */
}

.import{
  background-color: rgba(165, 214, 63, 0.71);
  border: 2px solid  #9caf70;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效 */
  padding: 10px 20px;
  font-size: 16px;
  margin-left: 80px; /* 根据需要调整 */
  width: 50%; /* 根据需要调整宽度 */
  cursor: pointer; /* 鼠标悬停时显示手型图标 */
  transition: background-color 0.3s; /* 背景色变化的过渡效果 */
  margin-top: 20px;
}

.upload-icon{
  width: 20px;
  height:20px;
  margin: 15px 15px;
}
table {
  margin-top: 20px;
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed; /* 使用固定布局以保持列宽一致 */
  align-items: center; /* 垂直居中子元素 */
  justify-content: space-between; /* 水平分布子元素 */
  border: 2px solid  #9caf70;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效 */
}

th, td {
  border: 1px solid #ddd;
  padding: 2px; /* 根据需要调整内边距 */
  font-size: 8px; /* 根据需要调整字体大小 */
  white-space: nowrap; /* 防止文本换行 */

}

th {
  background-color: #f2f2f2;
}



/* 媒体查询：对于较小的屏幕，进一步减小字体大小和内边距 */
@media (max-width: 768px) {
  th, td {
    padding: 5px;
    font-size: 10px;
  }
}
.scores-detail {
  padding: 10px;
  font-family: Arial, sans-serif;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
}


</style>